import axios from 'axios';
import { ACCESS_TOKEN } from '@/mutation-type';
import { webStorage } from '@/utils/webStorage';
import { useUserStore } from '@/store/user';
import { notification, Modal } from 'ant-design-vue';

const service = axios.create({
	baseURL: import.meta.env.VITE_APP_BASE_API, // api base_url
	timeout: 9000 // 请求超时时间
});

//请求拦截
service.interceptors.request.use(
	config => {
		const token = webStorage.ls.get(ACCESS_TOKEN);
		if (token) {
			config.headers['X-Access-Token'] = token;
		}
		return config;
	},
	error => {
		console.log(error);
		return Promise.reject(error);
	}
);
//请求响应
service.interceptors.response.use(
	response => {
		return response.data;
	},
	err => {
		if (err.response) {
			const data = err.response.data;
			const token = webStorage.ls.get(ACCESS_TOKEN);
			switch (err.response.status) {
				case 401:
					notification.error({ message: '系统提示', description: '未授权，请重新登录', duration: 4 });
					if (token) {
						let user = useUserStore();
						user.logout().then(res => {
							window.location.reload();
						});
					}
					break;
				case 403:
					notification.error({ message: '系统提示', description: '拒绝访问', duration: 4 });
					break;
				case 404:
					notification.error({ message: '系统提示', description: '很抱歉，资源未找到!', duration: 4 });
					break;
				case 500:
					if (token && data.message.includes('Token失效')) {
						Modal.error({
							title: '登录已过期',
							content: '很抱歉，登录已过期，请重新登录',
							okText: '重新登录',
							mask: false,
							onOk: () => {
								let user = useUserStore();
								user.logout().then(res => {
									window.location.reload();
								});
							}
						});
					} else {
						message.error(data.message);
					}
					break;
				case 504:
					notification.error({ message: '系统提示', description: '网关超时' });
					break;
				default:
					notification.error({
						message: '系统提示',
						description: data.message,
						duration: 4
					});
					break;
			}
		}
		return Promise.reject(err);
	}
);

export { service as axios };
